import {Injectable} from "@nestjs/common";
import {Cron, CronExpression, Interval} from '@nestjs/schedule';
import ILogger from "@/services/logger.service";
import IGlobal from "@/services/global.service";
import { DbService } from "@/db/db.service";
import { concatMap, defer, from, map, of } from "rxjs";
import axios from "axios";
import * as moment from "moment"
import IHelper from "@/services/helper.service";
import { AuthService } from "../auth/auth.service";

@Injectable()
export class ScheduleService {
  constructor(
    private readonly dbService: DbService,
  ) {}
  @Cron(CronExpression.EVERY_3_HOURS)
  exampleHandler() {
    ILogger.info(`exampleHandler triggered.`)
  }

  @Cron(CronExpression.EVERY_MINUTE)
  hookAccountUserActionHandler() {
    if (!IHelper.hookTimeAvailable()) return
    this.dbService.accountRepository.findBy({hook_user_action: 1}).then(accounts => {
      if (accounts.length > 0) {
        accounts.forEach(account => {
          ILogger.info(`fire-hook-user-action ${IGlobal.appUrl}/account/${account.id}/fire-hook-user-action`)
          axios.get(`${IGlobal.appUrl}/account/${account.id}/fire-hook-user-action`).then(e => e).catch(e => e)
        })
      }
    })
  }

  @Cron(CronExpression.EVERY_MINUTE)
  closeSpiderBrowserHandler() {
    return
    console.log("IGlobal.store.spiderBrowser1", IGlobal.store.spiderBrowser)
    if (!Array.isArray(IGlobal.store.spiderBrowser)) return
    IGlobal.store.spiderBrowser.forEach((item, idx) => {
      if (Date.now() - item.startAt > 2 * 60 * 1000) {
        item.browser.close().catch(e => e)
        IGlobal.store.spiderBrowser.splice(idx, 1)
      }
    })
  }

  @Cron(CronExpression.EVERY_MINUTE)
  startSpiderBrowserHandler() {
    return
    console.log("IGlobal.store.spiderBrowser2", IGlobal.store.spiderBrowser)
    axios.get(`${IGlobal.appUrl}/debug/mod/4`)
  }

  @Cron(CronExpression.EVERY_MINUTE)
  bindTaskCheckHandler() {
    // ILogger.info(`biliAuthTaskCheckHandler triggered.`)
    Object.values(IGlobal.bindAccountTaskSet).forEach(task => {
      if (task) {
        // 5 min expired
        if ((Date.now() - task.startAt) > 5 * 60 * 1000) {
          task.browser.close().then(e => e).catch(e => e).then(() => {
            ILogger.info(`Task ${task.hash} expired, auto close puppeteer browser`)
          })
          IGlobal.bindAccountTaskSet[task.hash] = undefined
        }
      }
    })
  }

  @Cron(CronExpression.EVERY_3_HOURS)
  accountBindStatusCheckHandler() {
    // @id:BeardedBear.beardedtheme Black & Amethyst Soft
    from(this.dbService.accountRepository.findBy({status: 1})).pipe(
      map(list => {
        list.forEach(item => {
          axios.get(`${IGlobal.appUrl}/account/${item.id}/check-cookie`).catch(e => e)
        })
      })
    ).subscribe()
    
  }

  @Cron(CronExpression.EVERY_MINUTE)
  runFfmpegHanler() {
    if (+IGlobal.store?.taskSettings?.autoFetch === 1 && IGlobal.store.getPubVideoQueue.length > 0) {
      const runningTask = IGlobal.store.getPubVideoQueue.find(e => e.state === "running")
      if (runningTask) return
      let nextTask = [...IGlobal.store.getPubVideoQueue].pop()
      ILogger.info(`后台自动启动ffmpeg转码`)
      axios.post(
        `${IGlobal.appUrl}/pub/task/${nextTask.id}/get_video`,
        {...nextTask.config},
        {
          headers: {
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Authorization': nextTask.authorization,
            'Connection': 'keep-alive',
            'Origin': 'https://vpuber-proxy.frp.wonew.top',
            'Referer': 'https://vpuber-proxy.frp.wonew.top/',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-site',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
            'sec-ch-ua': '"Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"'
          }
        }
      ).then(e => {
        ILogger.info(`w323 ${JSON.stringify(e.data)}`)
      }).catch(e => e)
    }
  }
}